package com.hypo.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hypo.mapper.ClazzMapper;
import com.hypo.mapper.StudentMapper;
import com.hypo.pojo.Clazz;
import com.hypo.until.MyException;
import com.hypo.pojo.PageResult;
import com.hypo.pojo.QueryString;
import com.hypo.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public int add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        int add = clazzMapper.add(clazz);
        return add;
    }

    @Override
    public List<Clazz> findAll() {
        List<Clazz> all = clazzMapper.findAll();
        return all;
    }

    @Override
    public PageResult page(QueryString queryString) {
        PageHelper.startPage(queryString.getPage(), queryString.getPageSize());
        List<Clazz> list = clazzMapper.list(queryString);
        list.forEach(clazz -> {
            if (LocalDate.now().isBefore(clazz.getBeginDate())) {
                clazz.setStatus("未开课");
            } else if (LocalDate.now().isAfter(clazz.getEndDate())) {
                clazz.setStatus("已结课");
            } else {
                clazz.setStatus("在读");
            }
        });
        Page<Clazz> clazzPage = (Page<Clazz>) list;
        return new PageResult(clazzPage.getTotal(), list);
    }

    @Override
    public Integer delClass(Integer id) {
        Integer num = studentMapper.queryId(id);
        if (num != null) {
            throw MyException.clazz();
        } else {
            return clazzMapper.delClass(id);
        }
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public Integer modify(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        return clazzMapper.modify(clazz);
    }
}
